package com.ossjk.oa.attendance.controller;

import java.io.InputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.ossjk.core.base.controller.BaseController;
import com.ossjk.core.util.CommonUtil;
import com.ossjk.oa.attendance.entity.Atdreport;
import com.ossjk.oa.attendance.entity.Atdtable;
import com.ossjk.oa.attendance.entity.Attendance;
import com.ossjk.oa.attendance.service.IAtdreportService;
import com.ossjk.oa.attendance.service.IAtdtableService;
import com.ossjk.oa.attendance.service.IAttendanceService;
import com.ossjk.oa.system.entity.Department;
import com.ossjk.oa.system.service.IDepartmentService;
import com.ossjk.oa.system.service.IEmployeeService;
import com.ossjk.oa.system.vo.EmployeeVo;

/**
 * <p>
 * 考勤 前端控制器
 * </p>
 *
 * @author chair
 * @since 2019-02-03
 */
@RestController
@RequestMapping("/attendance/calendar")
public class CalendarController extends BaseController {
	@Autowired
	private IAttendanceService iAttendanceService;
	@Autowired
	private IAtdreportService iAtdreportService;
	@Autowired
	private IEmployeeService iEmployeeService;
	@Autowired
	private IDepartmentService iDepartmentService;
	@Autowired
	private IAtdtableService iAtdtableService;

	@RequiresPermissions("00050035")
	@GetMapping("/list")
	public Object list(String selectedtime, String did, String eid) {
		List list = null;
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
			Date strToDate = sdf.parse(selectedtime);
			Wrapper wrapper = Condition.create().isWhere(true).orderBy("type", false);
			if (!CommonUtil.isBlank(did)) {
				wrapper.eq("a.did", did);
			}
			if (!CommonUtil.isBlank(eid)) {
				wrapper.eq("a.eid", eid);
			} else {
				// 默认查询自己
				//if (CommonUtil.isBlank(did)) {
					wrapper.eq("a.eid", getCurrnetUserId());
				//}
			}
			// 获取现在时间
			Date date = new Date();
			Calendar cal = Calendar.getInstance();
			cal.setTime(strToDate);// 设置起时间

			// 减少一个月 
			cal.add(Calendar.MONTH, -1);
			date = cal.getTime();
			wrapper.ge("a.date", date);

			// 增加一个月
			cal.add(Calendar.MONTH, +2);
			date = cal.getTime();
			wrapper.le("a.date", date);

			list = iAttendanceService.selectCalendar(wrapper);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return responseSuccess(list);
	}

	@RequiresPermissions("00050035")
	@GetMapping("/listDetail")
	public Object listDetail(String eid, String date) {
		Wrapper wrapper = Condition.create().isWhere(true).ne("ad.isdelete", "2").orderBy("ad.crtm", true);
		if (!CommonUtil.isBlank(eid)) {
			wrapper.eq("ad.eid", eid);
		} else {
			wrapper.eq("ad.eid", getCurrnetUserId());
		}
		if (!CommonUtil.isBlank(date)) {
			try {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
				Date strToDate = sdf.parse(date);
				wrapper.eq("ad.date", strToDate);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}

		return responseSuccess(iAttendanceService.selectDetail(wrapper));
	}

	@RequiresPermissions("00050035")
	@GetMapping("/toListDetail")
	public Object toListDetail(String eid, String date) {
		Wrapper wrapper = Condition.create().isWhere(true).ne("ad.isdelete", "2").orderBy("ad.crtm", true);
		if (!CommonUtil.isBlank(eid)) {
			wrapper.eq("ad.eid", eid);
		} else {
			wrapper.eq("ad.eid", getCurrnetUserId());
		}
		if (!CommonUtil.isBlank(date)) {
			try {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
				Date strToDate = sdf.parse(date);
				wrapper.eq("ad.date", strToDate);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}

		return responseSuccess(iAttendanceService.selectDetail(wrapper));
	}

	@RequiresPermissions("00050035")
	@PostMapping("/insert")
	public Object insert(Attendance attendance) {

		if (iAttendanceService.insert(attendance)) {
			return responseSuccess();
		} else {
			return responseFail();
		}
	}

	@RequiresPermissions("00050035")
	@GetMapping("/toUpdate/{id}")
	public Object toUpdate(@PathVariable("id") String id) {
		return responseSuccess(iAttendanceService.selectById(id));
	}

	@RequiresPermissions("00050035")
	@PutMapping("/update")
	public Object update(Attendance attendance) {
		if (iAttendanceService.updateById(attendance)) {
			return responseSuccess();
		} else {
			return responseFail();
		}

	}

	@RequiresPermissions("000500350005")
	@GetMapping("/geneAtdTable")
	public Object geneAtdTable(String year, String month) {
		String eid = getCurrnetUserId();
		Map data = new HashMap<>();
		Wrapper wrapper = Condition.create().isWhere(true).eq("e.id", eid).eq("e.isdelete", 1);
		EmployeeVo employeeVo = iEmployeeService.selectVo(wrapper);
		Department department = iDepartmentService.selectByEid(eid);
		// 查询报表是否已经确认
		Wrapper wrapper2 = Condition.create().eq("eid", eid).eq("did", employeeVo.getDid()).eq("year", year).eq("month", month);
		Atdtable atdtable = iAtdtableService.selectOne(wrapper2);

		String date = year + "-" + month;
		int shouldAttd = 0;
		if (!CommonUtil.isBlank(atdtable)) {
			// 查询应出勤
			shouldAttd = atdtable.getShouldAttd().intValue();
			if (CommonUtil.isEquals(atdtable.getIsConfirmed(), 1)) {
				return responseFail("报表已确认！");
			}
		} else {
			// 没有生成过报表
			// 查询应出勤
			StringBuffer sb = new StringBuffer();
			try {
				URL u = new URL("https://tool.bitefu.net/jiari/" + "?d=" + date + "&info=1");// 获取连接对象
				HttpURLConnection conn = (HttpURLConnection) u.openConnection();
				// 连接
				conn.connect();
				// 获取输入流
				InputStream in = conn.getInputStream();
				// 读取输入流
				int r;
				byte[] bs = new byte[1024];
				while ((r = in.read(bs)) != -1) {
					sb.append(new String(bs, 0, r));
				}
				in.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			JSONObject jsonObject = JSONObject.parseObject(sb.toString());
			for (String str : jsonObject.keySet()) {
				jsonObject = (JSONObject) jsonObject.get(str);
				for (String str2 : jsonObject.keySet()) {
					JSONObject day = (JSONObject) jsonObject.get(str2);
					if (CommonUtil.isEquals(day.get("type"), 0)) {
						shouldAttd++;
					}
				}
			}
		}
		Wrapper wrapper3 = Condition.create().eq("eid", eid).eq("year", year).eq("month", month);
		int actualAttd = iAttendanceService.selectCount(wrapper3);
		List<Attendance> attendances = iAttendanceService.selectList(wrapper3);
		int lateAndEarlyLeave = 0;
		for (Attendance attendance : attendances) {
			// 状态异常
			if (CommonUtil.isEquals(attendance.getStat(), 2)) {
				// 有签入签出时间
				if (!CommonUtil.isBlank(attendance.getCkin()) && !CommonUtil.isBlank(attendance.getCkot())) {
					// 迟到
					if (department.getBgtm().before(attendance.getCkin())) {
						lateAndEarlyLeave += CommonUtil.diff(attendance.getCkin(), department.getBgtm(), "MINUTES");
						System.out.println("迟到"+CommonUtil.diff(attendance.getCkin(), department.getBgtm(), "MINUTES"));
					}
					// 早退
					if (department.getEdtm().after(attendance.getCkot())) {
						lateAndEarlyLeave += CommonUtil.diff(department.getEdtm(),attendance.getCkot(),  "MINUTES");
						System.out.println("早退"+CommonUtil.diff(department.getEdtm(), attendance.getCkot(), "MINUTES"));
					}
				}
			}
		}

		Wrapper wrapper4 = Condition.create().eq("eid", eid).eq("did", department.getId()).eq("rwst", "2").eq("year", year).eq("month", month);
		List<Atdreport> atdreports = iAtdreportService.selectList(wrapper4);
		int overtime = 0;
		float paidAnnualLeave = 0;
		float paidLeave = 0;
		float generalLeave = 0;
		float goout = 0;
		float absenteeism = 0;
		for (Atdreport atdreport : atdreports) {
			// 加班
			if (CommonUtil.isEquals(atdreport.getType(), 1)) {
				overtime += atdreport.getDuration().intValue();
				// 带薪年假
			} else if (CommonUtil.isEquals(atdreport.getType(), 2)) {
				if (CommonUtil.isEquals(atdreport.getDuration(), 3)) {
					paidAnnualLeave += 1;
				} else {
					paidAnnualLeave += 0.5;
				}
				// 带薪调休
			} else if (CommonUtil.isEquals(atdreport.getType(), 3)) {
				if (CommonUtil.isEquals(atdreport.getDuration(), 3)) {
					paidLeave += 1;
				} else {
					paidLeave += 0.5;
				}
				// 普通请假
			} else if (CommonUtil.isEquals(atdreport.getType(), 4)) {
				if (CommonUtil.isEquals(atdreport.getDuration(), 3)) {
					generalLeave += 1;
				} else {
					generalLeave += 0.5;
				}
				// 外出
			} else if (CommonUtil.isEquals(atdreport.getType(), 5)) {
				if (CommonUtil.isEquals(atdreport.getDuration(), 3)) {
					goout += 1;
				} else {
					goout += 0.5;
				}
			}
		}
		atdreports = null;
		absenteeism = shouldAttd - actualAttd - paidLeave - paidAnnualLeave - generalLeave;
		absenteeism = absenteeism < 0 ? 0 : absenteeism;
		atdtable = new Atdtable();
		atdtable.setYear(year);
		atdtable.setEid(employeeVo.getId());
		atdtable.setDid(employeeVo.getDid());
		atdtable.setMonth(month);
		atdtable.setShouldAttd(new BigDecimal(shouldAttd));
		atdtable.setActualAttd(new BigDecimal(actualAttd));
		atdtable.setLateAndEarlyLeave(new BigDecimal(lateAndEarlyLeave));
		atdtable.setOvertime(new BigDecimal(overtime));
		atdtable.setPaidAnnualLeave(new BigDecimal(paidAnnualLeave));
		atdtable.setPaidLeave(new BigDecimal(paidLeave));
		atdtable.setGeneralLeave(new BigDecimal(generalLeave));
		atdtable.setGoout(new BigDecimal(goout));
		atdtable.setAbsenteeism(new BigDecimal(absenteeism));
		atdtable.setIsConfirmed(new BigDecimal(2));
		if (iAtdtableService.geneAtdTable(atdtable)) {
			return responseSuccess("生成报表成功，请到个人考勤报表查看。");
		} else {
			return responseFail();
		}

	}

	@RequiresPermissions("00050035")
	@DeleteMapping("/delete/{id}")
	public Object delete(@PathVariable("id") String[] id) {
		if (iAttendanceService.deleteBatchIds(Arrays.asList(id))) {
			return responseSuccess();
		} else {
			return responseFail();
		}
	}

}
